package mia.beans;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import mia.dao.AdvertisementEntityDAO;
import mia.dao.CategoryEntityDAO;
import mia.entity.AdvertisementEntity;
import mia.entity.CategoryEntity;
import mia.entity.UserEntity;
import mia.util.HibernateManager;

@ManagedBean(name = "categoryBean")
@RequestScoped
public class CategoryBean {

	@ManagedProperty("#{userLoginBean.user}")
	private UserEntity user;

	private Map<String, CategoryEntity> categories = null;
	private List<CategoryEntity> allCategories = CategoryEntityDAO
			.searchCategories("");
	private String addedCategory;
	private String parentName;
	private String editParentName = "";
	private CategoryEntity selectedCategory = new CategoryEntity();
	private CategoryEntity selectedCategoryEdit = new CategoryEntity();
	private CategoryEntity selectedCategoryDelete = new CategoryEntity();
	private Boolean active = false;

	public UserEntity getUser() {
		return user;
	}

	public void setUser(UserEntity user) {
		this.user = user;
	}

	public Map<String, CategoryEntity> getCategories() {
		categories = CategoryEntityDAO.getCategories();
		return categories;
	}

	public void setCategories(Map<String, CategoryEntity> categories) {
		this.categories = categories;
	}

	public List<CategoryEntity> getAllCategories() {
		return allCategories;
	}

	public void setAllCategories(List<CategoryEntity> allCategories) {
		this.allCategories = allCategories;
	}

	public String getAddedCategory() {
		return addedCategory;
	}

	public void setAddedCategory(String addedCategory) {
		this.addedCategory = addedCategory;
	}

	public String getParentName() {
		return parentName;
	}

	public void setParentName(String parentName) {
		this.parentName = parentName;
	}

	public String getEditParentName() {
		return editParentName;
	}

	public void setEditParentName(String editParentName) {
		this.editParentName = editParentName;
	}

	public CategoryEntity getSelectedCategory() {
		return selectedCategory;
	}

	public void setSelectedCategory(CategoryEntity selectedCategory) {
		this.selectedCategory = selectedCategory;
	}

	public CategoryEntity getSelectedCategoryEdit() {
		return selectedCategoryEdit;
	}

	public void setSelectedCategoryEdit(CategoryEntity selectedCategoryEdit) {
		this.selectedCategoryEdit = selectedCategoryEdit;
	}

	public CategoryEntity getSelectedCategoryDelete() {
		return selectedCategoryDelete;
	}

	public void setSelectedCategoryDelete(CategoryEntity selectedCategoryDelete) {
		this.selectedCategoryDelete = selectedCategoryDelete;
	}

	public Boolean getActive() {
		return active;
	}

	public void setActive(Boolean active) {
		this.active = active;
	}

	public void tryAdd() {
		FacesContext context = FacesContext.getCurrentInstance();
		CategoryEntity cat = new CategoryEntity();

		if (addedCategory.isEmpty()) {
			context.addMessage("adding", new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Pole \"Nazwa kategorii\" nie może być puste!", ""));

		} else {
			CategoryEntity thisCategory = CategoryEntityDAO
					.getCategoryByName(addedCategory);
			if (thisCategory != null) {

				context.addMessage("adding", new FacesMessage(
						FacesMessage.SEVERITY_ERROR,
						"Kategoria o wskazanej nazwie istnieje!", ""));

			} else {
				cat.setActive(active);
				cat.setName(addedCategory);
				cat.setParentCategory(CategoryEntityDAO
						.getCategoryByName(parentName));
				cat.setOwner(user);

				if (HibernateManager.trySave(cat)) {
					context.addMessage("adding", new FacesMessage(
							FacesMessage.SEVERITY_INFO, "Dodano kategorię", ""));
					allCategories = CategoryEntityDAO.searchCategories("");

				} else {
					context.addMessage("adding", new FacesMessage(
							FacesMessage.SEVERITY_ERROR,
							"Nie udało się dodać kategorii!", ""));

				}
			}
		}
	}

	public void tryEdit() {

		FacesContext context = FacesContext.getCurrentInstance();
		if (selectedCategoryEdit.getName().isEmpty()) {
			context.addMessage("change", new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Pole \"Nazwa kategorii\" nie może być puste!", ""));
		} else {
			CategoryEntity checkCategory = CategoryEntityDAO
					.getCategoryByName(selectedCategoryEdit.getName());

			if (checkCategory == null
					|| (checkCategory != null && checkCategory.getCategory_id() == selectedCategoryEdit
							.getCategory_id())) {
				Session session = HibernateManager.getSession();
				session.beginTransaction();

				CategoryEntity thisCategory = CategoryEntityDAO
						.getCategoryById(session,
								selectedCategoryEdit.getCategory_id());

				if (!thisCategory.getName().equals(
						selectedCategoryEdit.getName()))
					thisCategory.setName(selectedCategoryEdit.getName());

				if (!thisCategory.isActive() == selectedCategoryEdit.isActive())
					thisCategory.setActive(selectedCategoryEdit.isActive());

				if (!thisCategory.getOwner().equals(user))
					thisCategory.setOwner(user);

				try {
					session.save(thisCategory);
					session.getTransaction().commit();
					context.addMessage("changing", new FacesMessage(
							FacesMessage.SEVERITY_INFO,
							"Dane zostały zmienione!", ""));
				} catch (Exception ex) {
					context.addMessage("changing",
							new FacesMessage(FacesMessage.SEVERITY_ERROR,
									"Spróbuj ponownie" + ex.getMessage(), ""));
					session.getTransaction().rollback();
				} finally {
					session.close();
					allCategories = CategoryEntityDAO.searchCategories("");
				}

			} else {
				context.addMessage("change", new FacesMessage(
						FacesMessage.SEVERITY_ERROR,
						"Nie można zmienić nazwy kategorii na podaną wartość!",
						""));
			}
		}
	}

	public void tryEditParent() {
		FacesContext context = FacesContext.getCurrentInstance();

		try {
			Session session = HibernateManager.getSession();
			session.beginTransaction();

			CategoryEntity thisCategory = CategoryEntityDAO.getCategoryById(
					session, selectedCategory.getCategory_id());

			thisCategory.setParentCategory(CategoryEntityDAO
					.getCategoryByName(editParentName));
			try {
				
				session.save(thisCategory);
				session.getTransaction().commit();
				System.out.println("Tu");
				context.addMessage("change", new FacesMessage(
						FacesMessage.SEVERITY_INFO, selectedCategory.getName()
								+ ":Zmieniono kategorię nadrzędną!", ""));
				allCategories = CategoryEntityDAO.searchCategories("");
			} catch (Exception ex) {
				session.getTransaction().rollback();
				context.addMessage("change", new FacesMessage(
						FacesMessage.SEVERITY_ERROR,
						"Wystąpił błąd, przepraszamy! ", ""));
				ex.printStackTrace();
			} finally {
				session.close();
			}
		} catch (Exception ex) {

			context.addMessage("change", new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Wystąpił błąd, przepraszamy!", ""));

		}
	}

	public void deleteCategory() {
		FacesContext context = FacesContext.getCurrentInstance();
		try
		{
			Session session = HibernateManager.getSession();
			session.beginTransaction();
			
			Criteria crit = session.createCriteria(AdvertisementEntity.class);
			if(selectedCategoryDelete  != null)
			{
				int id = selectedCategoryDelete.getCategory_id();
				selectedCategoryDelete = CategoryEntityDAO.getCategoryById(session, id);
				
				crit.add(Restrictions.eq("category", selectedCategoryDelete));
				List<AdvertisementEntity> lista_ogloszen = crit.list();
				
				CategoryEntity brak_kategorii = CategoryEntityDAO.getCategoryById(session, 1);
		
				if(brak_kategorii != null)
				{
					for(AdvertisementEntity adv : lista_ogloszen)
						AdvertisementEntityDAO.changeCategoryForAdvertisement(adv.getAdvertisement_id(), 1);
					CategoryEntity parent = CategoryEntityDAO.getCategoryById(session, id);
					Collection<CategoryEntity> childs = parent.getChildCategory();
					
					CategoryEntity nowa_nadrzedna = parent.getParentCategory();
					
					for(CategoryEntity child : childs)
					{
						child.setParentCategory(nowa_nadrzedna);
						session.merge(child);
					}
					Query q2 = session
							.createQuery("delete from CategoryEntity where category_id = :cat");
					q2.setInteger("cat", selectedCategoryDelete.getCategory_id());
					q2.executeUpdate();
		
					session.getTransaction().commit();
					context.addMessage("deleting", new FacesMessage("Usunięto kategorię!",""));
				}
			}
			session.close();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			context.addMessage("deleting", new FacesMessage(FacesMessage.SEVERITY_ERROR,ex.getMessage()+ "Nie udało się usunąć kategorii!",""));
			
		}
	}

}
